using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.Common
{
    public class ValidationRulesLoader
    {
        private readonly IMongoCollection<RuleBase> rulesCollection;

        private readonly IMongoCollection<RuleBase> inactiveRulesCollection;

        public ValidationRulesLoader(IMongoCollection<RuleBase> rulesCollection, IMongoCollection<RuleBase> inactiveRulesCollection)
        {
            this.rulesCollection = rulesCollection;
            this.inactiveRulesCollection = inactiveRulesCollection;
        }

        public async Task<IEnumerable<RuleBase>> ReadRulesAsync()
        {
            var allRules = await rulesCollection.Find(new BsonDocument()).ToListAsync().ConfigureAwait(false);
            var inactiveRules = await inactiveRulesCollection.Find(_ => true).ToListAsync().ConfigureAwait(false);

            var activeRules = allRules.Where(r => inactiveRules.All(x => r.GetType().FullName != x.GetType().FullName));

            return activeRules;
        }

        public async Task<IEnumerable<string>> GetInactiveRuleNames()
        {
            var inactiveRules = await inactiveRulesCollection.Find(_ => true).ToListAsync().ConfigureAwait(false);
            return inactiveRules.Select(x => x.GetType().FullName);
        }
    }
}
